package com.element.security.server.config;

import com.element.security.constant.SecurityParams;
import com.element.security.model.entity.AuthUserE;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.HashMap;
import java.util.Map;

/**
 * 返回资源服务器数据配置
 * 很重要,资源服务器获取用户信息可在这里配置
 *
 * @auther zhangwj
 * @date 2021/4/14 下午3:15
 */
@Configuration
public class TokenEnhancerConfig implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken,
                                     OAuth2Authentication authentication) {
        if (null != authentication && null != authentication.getUserAuthentication()) {
            final Map<String, Object> additionalInfo = new HashMap<>(4);
            Authentication auth = authentication.getUserAuthentication();
            if (null != auth && null != auth.getPrincipal()) {
                AuthUserE user = (AuthUserE) auth.getPrincipal();
                if (null != user) {
                    additionalInfo.put(SecurityParams.RESPONSE_USER_ID, user.getUserId());
                }
                ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
            }
        }
        return accessToken;
    }
}
